package com.heatingcharge.security.util;

import com.alibaba.fastjson.JSON;
import com.heatingcharge.common.exception.BaseException;
import com.heatingcharge.common.util.R;
import com.heatingcharge.security.JwtUser;
import io.jsonwebtoken.Jwt;
import lombok.experimental.UtilityClass;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created with IntelliJ IDEA.
 * Description: heating_charge_server
 * User: Devin
 * Date: 2019-07-05
 * Time: 11:47
 */
@UtilityClass
public class SecurityUtil {
    /**
     * 获取用户信息
     * @param authentication
     * @return
     */
    private JwtUser getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof JwtUser) {
            return (JwtUser) principal;
        }
        return null;
    }
    /**
     * @Description 获取用户
     *
     **/
    public JwtUser getUser(){
        try {
            JwtUser jwtUser=(JwtUser) getAuthentication().getPrincipal();
            return jwtUser;
        } catch (Exception e) {
            throw new BaseException("登录状态过期", HttpStatus.UNAUTHORIZED.value());
        }
    }
    /**
     * 获取Authentication
     */
    private Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    public void writeJavaScript(R r, HttpServletResponse response) throws IOException {
        response.setStatus(r.getCode());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        //新增
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control","no-cache");
        PrintWriter printWriter = response.getWriter();
        printWriter.write(JSON.toJSONString(r));
        printWriter.flush();
    }
}
